#include"chat.h"

DLNode* phead=NULL;

int ServerPrepare()
{
        int sock=socket(AF_INET,SOCK_STREAM,0);
        if(sock<0)
        {
                perror("socker error");
                exit(1);
        }
        struct sockaddr_in host;//服务器主机
        host.sin_family=AF_INET;
        host.sin_port=htons(PORT);
        host.sin_addr.s_addr=inet_addr(IP);

        if(bind(sock,(struct sockaddr*)&host,sizeof(host))<0)
        {
                perror("bind error");
                exit(1);
        }
        if(listen(sock,5)<0)
        {
                perror("listen error");
                exit(1);
        }

        return sock;
}


void thread_fun(void* argument)
{
        int sock=(int)argument;
        char buf[NAMESIZE+MSGSIZE]={0};
        while(1)
        {
                int recv_size=recv(sock,buf,MSGSIZE+NAMESIZE,0);
                if(recv_size<=0)
                {
                        Erase(phead,sock);
                        break;
                }
                else
                {
                        DLNode*cur=phead->next;
                        while(cur!=NULL)
                        {
                                send(cur->value,buf,NAMESIZE+MSGSIZE,MSG_DONTWAIT);
                                cur=cur->next;
                        }
                }
        }
        close(sock);
}

void ServerWork(int sock)
{
        while(1)
        {
                int new_sock=accept(sock,NULL,NULL);
                if(new_sock<0)
                {
                        perror("accept error");
                        return;
                }
                PushFront(phead,new_sock);
                //开始线程处理
                pthread_t thread;
                pthread_create(&thread,NULL,(void*)thread_fun,(void*)new_sock);
                pthread_detach(thread);
        }
}

int main()
{
        int sock=ServerPrepare();
        //将头初始化为sock并没有实在意义(比起随便初始化为一个值，不如初始化为已存在的)
        phead=CreateNode(sock);
        ServerWork(sock);
        close(sock);
        return 0;
}